package personal.lijun.skeleton.web.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import personal.lijun.skeleton.springcloud.common.data.ApiResultListSet;
import personal.lijun.skeleton.springcloud.common.data.ApiResultSet;
import personal.lijun.skeleton.web.Exception.CallRpcServiceException;
import personal.lijun.skeleton.web.feign.CalendarServiceFeign;
import personal.lijun.skeleton.web.feign.CalendarUser;
import personal.lijun.skeleton.web.feign.Role;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * @Auther: lijun@sstcsoft.com
 * @Date: 2019/9/16 16:47
 */
@Deprecated
@Service
public class UserDetailsServiceImpl  implements UserDetailsService {

    private static  final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Resource
    private CalendarServiceFeign  calendarService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        CalendarUser user = calendarService.findUserByEmail(userName);
        if(user==null)
            throw new UsernameNotFoundException("用户：\""+userName+"\""+"不存在");
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        ApiResultListSet<Role> roleList = calendarService.findUserRoles(user.getId());
        if(roleList.getCode() != ApiResultSet.SUCCESS){
            StringBuilder sb = new StringBuilder();
            sb.append("错误编码(code):"+roleList.getCode());
            sb.append("\r\n");
            sb.append(roleList.getMessage());
            sb.append("\r\n");
            sb.append(roleList.getStackTrace());
            logger.error(sb.toString());
            throw new CallRpcServiceException(sb.toString());
        }

        for(Role role : roleList){
            grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
        }

        return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), grantedAuthorities);
    }
}
